# coding=utf-8
import os
import re
import sys
import traceback

import akshare as ak
import pandas
import pandas as pd
from loguru import logger

from models.stock_model import StockNumber, DayInfo
from mylib.download_all import analysis_stock
from mylib.mycsv import sort_csv


def run(d=1):
    if d:
        sz_index_df = ak.index_zh_a_hist(symbol="000001", period="daily")
        df_sorted = sz_index_df.sort_values(by='日期', ascending=False)
        df_sorted.to_csv("shanghai_index.csv", index=False)
    else:
        df_sorted = pd.read_csv('shanghai_index.csv')
    today_date = eval(str(list(df_sorted['日期'])[0]).replace('-', ''))
    return today_date


def get_vol_min(N, today_date, sn):
    sc = f'stocks/{sn.ts_code}.csv'
    if not os.path.exists(sc):
        return None, None
    df = pandas.read_csv(sc)
    if str(df['trade_date'][0]) != str(today_date):
        analysis_stock(sn)
        df = pandas.read_csv(sc)
    result_arr = []
    find_n = False
    for row in df.index:
        d = DayInfo(sn, df.loc[row])
        if find_n and d.pct_chg < N:
            break
        result_arr.append(d)
        if d.pct_chg > N:
            find_n = True

    res = re.findall('stocks/(.*).csv', sc)
    link_code_arr = res[0].split('.')
    link_code = f'{link_code_arr[1]}{link_code_arr[0]}'
    hyperlink = f'"https://xueqiu.com/S/{link_code}"'
    date_arr_hyp = f'{res[0]},=HYPERLINK({hyperlink})'
    return result_arr, date_arr_hyp


def get_all_stock_csv_path():
    for root, dirs, files in os.walk('stocks'):
        return [os.path.join(root, item) for item in files]


def logi(result_arr):
    tk, bk, pd = False, False, False
    all_low = [d.low for d in result_arr]

    exp_first_min = min(all_low[:-1])
    # 如果最近所有最低价大于最近大涨日最高价，腾空
    if result_arr[-1].high < exp_first_min:
        tk = True
        return tk, bk, pd

    all_min = min(all_low)
    # 如果最近所有最低价等于最近大涨日最低价，半空
    if result_arr[-1].low == all_min:
        bk = True
        return tk, bk, pd

    # 如果大涨日最低价介于今日最高最低之间，破低
    if result_arr[0].high > result_arr[-1].low >= result_arr[0].low:
        pd = True
        return tk, bk, pd

    return tk, bk, pd


if __name__ == '__main__':
    N = 5
    try:
        if len(sys.argv) == 2:
            N = int(sys.argv[1])
        else:
            N = 5
    except Exception as e:
        logger.error(e)
        N = 5
    D = True
    today_date = run(D)
    full_path_tk = f'{today_date}_bk_{N}_腾空.csv'
    full_path_bk = f'{today_date}_bk_{N}_半空.csv'
    full_path_pd = f'{today_date}_bk_{N}_破低.csv'
    f_tk = open(full_path_tk, 'w', encoding='utf-8')
    f_bk = open(full_path_bk, 'w', encoding='utf-8')
    f_pd = open(full_path_pd, 'w', encoding='utf-8')
    f_tk.write(f'TDate,间隔,涨幅,收盘价,行业,名称,代号,连接')
    f_bk.write(f'TDate,间隔,涨幅,收盘价,行业,名称,代号,连接')
    f_pd.write(f'TDate,间隔,涨幅,收盘价,行业,名称,代号,连接')
    df = pd.read_csv('cal_ops/all.csv')
    full_path_txt = f'{today_date}_get_bk_N{N}.txt'
    if os.path.exists(full_path_txt):
        os.remove(full_path_txt)
    logger.add(full_path_txt, format='{message}')
    n_arr = []
    ts_code_arr = []
    result_dict = {}
    for row in df.index:
        sn = StockNumber(df.loc[row])
        if 'ST' in sn.name:
            continue
        # if sn.name not in [
        #     '通威股份',
        #     '隆基绿能',
        # ]:
        #     continue
        try:
            result_arr, date_arr_hyp = get_vol_min(N, today_date, sn)
            if date_arr_hyp is None and result_arr is None:
                continue
            if len(result_arr) == 1 or len(result_arr) > 50:
                continue
            if result_arr[0].close < 5 or result_arr[0].close > 50:
                continue

            tk, bk, pd = logi(result_arr)
            """
                elf.name = sn.name
                self.ts_code = sn.ts_code
                self.industry = sn.industry
                self.trade_date = df_row_data['trade_date']
                self.open = df_row_data['open']
                self.high = df_row_data['high']
                self.low = df_row_data['low']
                self.close = float(df_row_data['close'])
                self.pre_close = df_row_data['pre_close']
                self.change = df_row_data['change']
                self.pct_chg = float(df_row_data['pct_chg'])
                self.vol = df_row_data['vol']
                self.amount = df_row_data['amount']
            """
            today_s = result_arr[0]
            recent_h_s = result_arr[-1]
            # aa.write(f'TDate,涨幅,间隔,收盘价,行业,名称,代号,连接')
            rhs_pct = round(recent_h_s.pct_chg, 2)
            w_msg = f'\n{recent_h_s.trade_date},{len(result_arr)},{rhs_pct},{today_s.close},' \
                    f'{sn.industry},{sn.name},{date_arr_hyp}'
            if tk:
                f_tk.write(w_msg)
                f_tk.flush()
            if bk:
                f_bk.write(w_msg)
                f_bk.flush()
            if pd:
                f_pd.write(w_msg)
                f_pd.flush()
        except Exception as e:
            print(e, traceback.format_exc())

    if os.path.exists(full_path_txt):
        os.remove(full_path_txt)

    f_tk.close()
    f_bk.close()
    f_pd.close()

    sort_csv(full_path_tk, ['间隔', '涨幅', '行业', '名称'], [True, False, True, True])
    sort_csv(full_path_bk, ['间隔', '涨幅', '行业', '名称'], [True, False, True, True])
    sort_csv(full_path_pd, ['间隔', '涨幅', '行业', '名称'], [True, False, True, True])
